package auth

import (
	"context"
	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/types"
	"portal/model"

	"github.com/Masterminds/squirrel"
)

type Permission struct {
	IsAdmin bool
	Name    string
	Value   interface{}
}

func AddPermission(sb squirrel.SelectBuilder, perm Permission) squirrel.SelectBuilder {
	if !perm.IsAdmin {
		return sb.Where(squirrel.Eq{perm.Name: perm.Value})
	}
	return sb
}

func IsRoleInclude(roleArr []*types.Role, roleId int64) bool {
	for _,val := range roleArr {
		if val.RoleId == roleId {
			return true
		}
	}
	return false
}

func HasPermission(menuModel model.SysMenuModel, ctx context.Context, perm string) error {
	// 该步骤可以在中间间中完成
	auth, err := GetAuth(ctx)
	if err != nil {
		return err
	}
	isAdmin := IsRoleInclude(auth.Roles, int64(common.SuperAdminId))
	if isAdmin {
		return nil
	}
	roleIds := make([]*int64, 0)
	for _, val := range auth.Roles {
		roleIds = append(roleIds, &val.RoleId)
	}
	if len(roleIds) <= 0 {
		return errorx.NewBizError(500, "no permitted")
	}
	//判断是否拥有获取列表权限
	//oper unrealized
	_, err = menuModel.GetOprPermission(ctx, nil, perm, roleIds)
	if err != nil {
		return errorx.NewBizError(500, err.Error())
	}
	return nil
}

func IsAdmin(ctx context.Context) (bool, error) {
	auth, err := GetAuth(ctx)
	if err != nil {
		return false, err
	}
	isAdmin := IsRoleInclude(auth.Roles, int64(common.SuperAdminId))
	if isAdmin {
		return true, nil
	}
	return false, nil
}

func GetRoles(ctx context.Context) ([]*types.Role, error) {
	auth, err := GetAuth(ctx)
	if err != nil {
		return nil, err
	}
	return auth.Roles, nil
}

func GetRoleIds(ctx context.Context) ([]*int64, error) {
	roles, err := GetRoles(ctx)
	if err != nil {
		return nil, err
	}
	roleIds := make([]*int64, 0)
	for _, val := range roles {
		roleIds = append(roleIds, &val.RoleId)
	}
	return roleIds, nil
}

func GetDeptId(ctx context.Context) (string, error) {
	auth, err := GetAuth(ctx)
	if err != nil {
		return "", err
	}
	return auth.DeptId, nil
}

func GetAuth(ctx context.Context) (*types.User, error) {
	userInfoAny := ctx.Value("auth")
	if userInfoAny == nil {
		return nil, errorx.NewBizError(501, "登录凭证过期")
	}
	auth, ok := userInfoAny.(types.User)
	if !ok {
		return nil, errorx.NewBizError(500, "userinfo error")
	}
	return &auth, nil
}
